package cn.com.headfree.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;

import com.gta.edu.sdk.common.dto.LogTranferDto;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import cn.com.headfree.server.dto.ScpFile;

public class ScpclientUtil {
	private static final Logger log = Logger.getLogger(ScpclientUtil.class);
	private static ScpclientUtil util = new ScpclientUtil();
	private Connection conn;
	private Session session;
	private static final String LOCAL_TEMP_PATH = "d:/var/temp";

	private ScpclientUtil() {
	}

	public static ScpclientUtil getInstance() {
		if (util == null) {
			util = new ScpclientUtil();
		}
		return util;
	}
	
	public String downFile(String fileName) throws Exception {
		File localTempPathFile = new File(LOCAL_TEMP_PATH);
		if (!localTempPathFile.exists()) {
			localTempPathFile.mkdirs();
		}
		try {
			this.getConnection();
			SCPClient scpClient = new SCPClient(this.conn);
			scpClient.get(LogTranferDto.getInstance().getRemoteLogRootPath() + "/" + fileName, LOCAL_TEMP_PATH);
			return LOCAL_TEMP_PATH + "/" + fileName;
		} finally {
			this.closeConnection();
		}
	}

	/**
	 * 从远程服务器上查询日志文件列表
	 * 2020年5月20日 下午4:42:12
	 * @user fengya
	 * @param fileName
	 * @return
	 * @throws Exception
	 * @return List<ScpFile>
	 */
	public List<ScpFile> getRemoteFileList(String fileName) throws Exception {
		List<ScpFile> scpFileList = new ArrayList<ScpFile>();
		this.getConnection();
		InputStream is = null;
		BufferedReader brs = null;
		try {
			this.session.execCommand("wc -c " + LogTranferDto.getInstance().getRemoteLogRootPath() + "/*" + (fileName == null ? "" : fileName.trim()) + "*");
			is = new StreamGobbler(session.getStdout());// 获得标准输出流
			brs = new BufferedReader(new InputStreamReader(is));
			ScpFile file = null;
			for (String line = brs.readLine(); line != null; line = brs.readLine()) {
				file = this.getLogTranferFileDto(line);
				if (file !=null) {
					scpFileList.add(file);
				}
			}
			Collections.sort(scpFileList);
		} finally {
			if (is != null) {
				is.close();
			}
			if (brs != null) {
				brs.close();
			}
			this.closeConnection();
		}
		return scpFileList;
	}
	
	/**
	 * 解析文件信息获取文件名和文件大小
	 * 2020年5月20日 下午2:57:56
	 * @user fengya
	 * @param fileInfo
	 * @return
	 * @return LogTranferFileDto
	 */
	private ScpFile getLogTranferFileDto(String fileInfo) {
		String filelName = null;
		long fileSize = 0;
		String[] fileStrings = fileInfo.trim().split(" ");
		if (fileStrings.length == 2) {
			if (fileStrings[1].trim().contains(".log")) {
				fileSize = Long.parseLong(fileStrings[0].trim());
				filelName = fileStrings[1].trim().replace(LogTranferDto.getInstance().getRemoteLogRootPath() + "/", "");
				return new ScpFile(filelName, fileSize);
			}
		}
		return null;
	}
	
	/**
	 * 获取连接和会话 2020年5月20日 下午2:50:56
	 * 
	 * @user fengya
	 * @param @throws Exception
	 * @return void
	 */
	private void getConnection() throws Exception {
		conn = new Connection(LogTranferDto.getInstance().getRemoteIp(), LogTranferDto.getInstance().getRemotePort());
		conn.connect();
		// 鐧诲綍
		boolean isAuthenticated = conn.authenticateWithPassword(LogTranferDto.getInstance().getRemoteUserName(), LogTranferDto.getInstance().getRemotePassword());
		if (isAuthenticated == false) {
			throw new Exception("用户登录远程服务器失败！");
		}
		session = conn.openSession();
	}

	/**
	 * 关闭连接和会话 2020年5月20日 下午2:53:41
	 * 
	 * @user fengya
	 * @param
	 * @return void
	 */
	private void closeConnection() {
		if (this.session != null) {
			this.session.close();
			this.session = null;
		}
		if (this.conn != null) {
			conn.close();
			conn = null;
		}
	}

}
